const {
	Service
} = require("uni-cloud-router");
const jqlHandler = require('gd-accbuild-jql-handler')
const generateId = require('generate-id')
module.exports = class MetaMgrService extends Service {
	async generateCode({
		strategyName,
		params,
		data,
		vmCode: crudVmCode,
		dbJql
	}) {
		let ret = {
			errCode: -1,
			errMsg: '',
		}
		if (data.generateAlgorithm === "regex") {
			const reg = new RegExp(data.expression)
			const code = await generateId(data)
			if (data.isUnique) {
				const allRes = await Promise.all([
					dbJql.collection(data.tableName).where({
						[data.fieldName]: code
					}).limit(1).get(),
					dbJql.collection("gd_sys_generate_code_temp").where({
						table_name: data.tableName,
						field_name: data.fieldName,
						code
					}).limit(1).get()
				]);
				if (allRes.every(r => r.errCode === 0 && (Array.isArray(r.data) && r.data.length === 0))) {
					dbJql.collection("gd_sys_generate_code_temp").add({
						table_name: data.tableName,
						field_name: data.fieldName,
						code
					})
					ret = {
						errCode: 0,
						errMsg: '',
						data: {
							data: {
								code
							}
						}
					}
				} else {
					ret = {
						errCode: -1,
						errMsg: '生成的编号已存在,请重新生成',
						data: {
							data: {}
						}
					}
				}
			} else {
				ret = {
					errCode: 0,
					errMsg: '',
					data: {
						data: {
							code
						}
					}
				}
			}
		} else {

		}
		return ret
	}
	async resetDatabaseTableId({
		strategyName,
		params,
		data,
		vmCode: crudVmCode,
		dbJql
	}) {
		let ret = {
			errCode: 0,
			errMsg: '',
			data: {}
		}
		if (data.hasOwnProperty("tableName")) {
			const res = await dbJql.collection(data.tableName).get();
			if (res.errCode === 0 && Array.isArray(res.data)) {
				res.data.forEach((el, idx) => {
					let val = idx + 1;
					let isBreakCond = false
					if (!isBreakCond && val < 10) {
						val = `000000000000000000${val}`
						isBreakCond = true
					} else if (!isBreakCond && val < 100) {
						val = `00000000000000000${val}`
						isBreakCond = true
					}else if (!isBreakCond && val < 1000) {
						val = `0000000000000000${val}`
						isBreakCond = true
					}else if (!isBreakCond && val < 10000) {
						val = `000000000000000${val}`
						isBreakCond = true
					}
					dbJql.collection(data.tableName).where({
						id: el.id
					}).update({
						id: val
					})
				});
				ret = {
					errCode: 0,
					errMsg: '',
					data: {}
				}
			}
		} else {
			ret = {
				errCode: -1,
				errMsg: '',
				data: {}
			}
		}
		return ret
	}
}
